export class ElasticsearchQuery {
  private must = [];

  term(key: string, value: string | number | boolean | number[]) {
    if (typeof value !== 'undefined') {
      if (Array.isArray(value)) {
        this.must.push({ terms: { [key]: value } });
      } else {
        this.must.push({ term: { [key]: value } });
      }
    }
    return this;
  }

  match(key: string, value: string | number) {
    if (typeof value !== 'undefined') {
      this.must.push({ match: { [key]: value } });
    }
    return this;
  }

  bool(keys: string, value: string | number) {
    if (typeof value !== 'undefined') {
      const should = [];
      for (const key of keys.split(',')) {
        should.push({
          term: {
            [key]: value,
          },
        });
      }
      this.must.push({
        bool: {
          should,
        },
      });
    }

    return this;
  }

  shouldMatch(keys: string, value: string | number) {
    if (typeof value !== 'undefined') {
      const should = [];
      for (const key of keys.split(',')) {
        should.push({
          match: {
            [key]: value,
          },
        });
      }
      this.must.push({
        bool: {
          should,
        },
      });
    }

    return this;
  }

  range(key: string, gte: number, lte: number) {
    if (gte && lte) {
      this.must.push({ range: { [key]: { gte, lte } } });
    }
    return this;
  }

  build() {
    return this.must;
  }
}
